package com.xtool.livewallpaper.local

import android.graphics.Rect
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.xtool.livewallpaper.base.dp
import com.xtool.livewallpaper.data.VideoWallpaper
import com.xtool.livewallpaper.databinding.FragmentLocalBinding
import java.util.ArrayList

class LocalFragment : Fragment() {
    private val binding: FragmentLocalBinding by lazy { FragmentLocalBinding.inflate(layoutInflater) }
    private val viewModel: LocalWallpaperViewModel by viewModels()
    private val adapter: WallpaperAdapter by lazy { WallpaperAdapter({
        viewModel.load()
    }) }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    private fun init() {
        binding.recyclerView.visibility = View.VISIBLE
        binding.animationView.visibility = View.VISIBLE
        binding.animationView.playAnimation()
        binding.recyclerView.addItemDecoration(object : ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                val position = parent.getChildAdapterPosition(view)
                if (position % 2 == 0) {
                    outRect.set(16.dp, 5.dp, 5.dp, 5.dp)
                } else {
                    outRect.set(5.dp, 5.dp, 16.dp, 5.dp)
                }
            }
        })
        binding.recyclerView.layoutManager =
            StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        binding.recyclerView.adapter = adapter
        viewModel.files.observe(viewLifecycleOwner) {
            hideLoading()
            adapter.setData(ArrayList(it.map { VideoWallpaper(Uri.parse(it.absolutePath), 100, 100) }.toList()))
        }
        showLoading()
        viewModel.load()
    }

    private fun showLoading() {
        binding.animationView.visibility = View.VISIBLE
        binding.animationView.playAnimation()
    }

    private fun hideLoading() {
        binding.animationView.visibility = View.GONE
        binding.animationView.cancelAnimation()
    }
}